#include "widget.h"
#include "ui_widget.h"
#include <QTableWidgetItem>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //创建三行
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(1);
    ui->tableWidget->insertRow(2);

    //创建三列
    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(1);
    ui->tableWidget->insertColumn(2);

    //设置指定列的列名
    ui->tableWidget->setHorizontalHeaderItem(0,new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(1,new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(2,new QTableWidgetItem("年龄"));

    //插入数据
    ui->tableWidget->setItem(0,0,new QTableWidgetItem("1"));
    ui->tableWidget->setItem(0,1,new QTableWidgetItem("张三"));
    ui->tableWidget->setItem(0,2,new QTableWidgetItem("19"));

    ui->tableWidget->setItem(1,0,new QTableWidgetItem("2"));
    ui->tableWidget->setItem(1,1,new QTableWidgetItem("李四"));
    ui->tableWidget->setItem(1,2,new QTableWidgetItem("20"));

    ui->tableWidget->setItem(2,0,new QTableWidgetItem("3"));
    ui->tableWidget->setItem(2,1,new QTableWidgetItem("王五"));
    ui->tableWidget->setItem(2,2,new QTableWidgetItem("22"));
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_addRow_clicked()
{
    //获取当前有多少行
    int rowCount = ui->tableWidget->rowCount();
    //新增一行,参数的含义是新增的这一行插入到指定行
    ui->tableWidget->insertRow(rowCount);
}

void Widget::on_pushButton_delRow_clicked()
{
    //获取当前选中行的行号
    int curRow = ui->tableWidget->currentRow();
    //删除选中行
    ui->tableWidget->removeRow(curRow);
}

void Widget::on_pushButton_addCul_clicked()
{
    //获取当前已经有多少列了
    int rowCount = ui->tableWidget->columnCount();
    //插入一列
    ui->tableWidget->insertColumn(rowCount);
    //设置插入列的列名
    const QString &rowName = ui->lineEdit->text();
    ui->tableWidget->setHorizontalHeaderItem(rowCount,new QTableWidgetItem(rowName));
}

void Widget::on_pushButton_delCul_clicked()
{
     //获取选中列的列号
     int curCul = ui->tableWidget->currentColumn();
     //删除选中列
     ui->tableWidget->removeColumn(curCul);
}
